<template>
  <div>
    <div class="shopping-cart">
      <h2>购物车</h2>
      <div v-if="error">{{ error }}</div>
      <table v-else class="cart-table">
        <thead>
          <tr>
            <th><input type="checkbox" @change="updateAll()" v-model="bbb"/>全选</th>
            <th>商品信息</th>
            <th>价格</th>
            <th>数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(flower, index) in flowers" :key="flower.flower_id">
            <td><input type="checkbox" @change="updateSelectAll(index,flower.flowerId)" v-model="selectedItems[index]"/></td>
            <td>
              <div style="display: flex;align-items: center;">
                <img :src="flower.image" alt="flower" class="flower-img" />
                <div>{{ flower.use }}--{{ flower.material }}--{{ flower.category }}</div>
              </div>
            </td>
            <td style="color:red;">¥{{ flower.price }}</td>
            <td>{{ count[index] }}</td>
            <td>
              <button class="delete-btn" @click="deleteFlower(flower.flowerId)">删除</button>
              <button class="change-btn" @click="changeCount(flower,count[index])">修改</button>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="cart-footer">
        <button class="delete-selected-btn" @click="deleteSelectedFlowers">删除</button>
        <span>共 {{ totalCount }} 件商品</span>
        <span>应付金额: ¥{{ totalAmount }}</span>
        <button class="checkout-btn" @click="goToCreateOrder">结算</button>
      </div>


    </div>

    <!-- 新窗口 -->
    <el-dialog v-model="isShow" >
    <div class="dialog-content">
      <img :src="`${aaa.image}`" class="dialog-image">
      <div>
        <div style="font-size: 20px; font-weight: bold;">{{aaa.name}}</div>
        <hr>
        <div>种类：{{ aaa.material }}</div>
        <div>类别：{{ aaa.category }}</div>
        <div class="flower-info">
          <div>价格：</div>
          <div style="font-size: 18px; color:red">￥{{aaa.price}}</div>
        </div>
      </div>
    </div>
    <div>
      <el-input-number v-model="ccc" :min="1"  @change="handleChange" class="input-number"/>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="danger" @click="deleteFlower(aaa.flowerId)">删除</el-button>
          <el-button type="primary" @click="updateCount(aaa.flowerId)">修改</el-button>
      </div>
    </template>
  </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue';
import axios from '@/http/axios';
import { useRouter } from 'vue-router';
import { useLoginStore } from "@/stores/LoginStore";
const router = useRouter();

let flowers = ref([]);
let count = ref([]);
let error = ref('');
let userId = ref(1);
let aaa = reactive({ flowerId: 0, name: '', price: 0, use: '', material: '', category: '', image: '' });//选中花的信息
let ccc = ref(0);//修改选中的数量
let isShow = ref(false);//是否显示购物车为空的提示

const loginStore = useLoginStore();

function goToCreateOrder() {
  
  const idsStr = flowerIds.join(',')
  router.push({
    name:'createOrder',
    params: { userId: userId.value,flowerIds: idsStr }
  });
  
}


// 计算总商品数
const totalCount = computed(() => {
  return count.value.reduce((sum, curr) => sum + curr, 0);
});

// 计算总金额
const totalAmount = computed(() => {
  let total = 0;
  flowers.value.forEach((flower, index) => {
    total += flower.price * count.value[index];
  });
  return total.toFixed(2);
});

// 挂载时获取购物车数据
onMounted(async () => {
  const response = await axios.get(`/cart`, {
      headers: {
        'Authorization': loginStore.loginToken
      }
    });
    flowers.value = response.data.flowers;
    count.value = response.data.count;
    userId.value = response.data.userId;
});

async function deleteFlower(flowerId) {
  try {
    const response = await axios.delete(`/cart/deleteFlower/${userId.value}/${flowerId}`, {
      headers: {
        'Authorization': loginStore.loginToken
      }
    });
    window.location.reload();
    // 删除成功后刷新购物车数据
    // 判断是否刷新购物车数据
    if (response.data.flowers==null) {
      // 购物车为空，刷新页面
      console.log('购物车为空');
    } else {
      // 购物车不为空，刷新购物车数据
      isShow.value = false;
      flowers.value = response.data.flowers;
      count.value = response.data.count;
    }
  } catch (err) {
    //error.value = '删除失败';
    alert('删除失败');
    window.location.reload();
    console.error(err);
    
  }
}
function changeCount(flower,count) {
  ccc.value = count;
  aaa.flowerId = flower.flowerId;
  aaa.name = flower.name;
  aaa.price = flower.price;
  aaa.use = flower.use;
  aaa.material = flower.material;
  aaa.category = flower.category;
  aaa.image = flower.image;
  isShow.value = true
}
let bbb = ref(false);
// 全选/取消全选
function updateAll() {
  if(bbb.value){
    for(let i=0;i<flowers.value.length;i++){
      selectedItems[i] = true
    }
    for(let i=0;i<flowers.value.length;i++){
      flowerIds.push(flowers.value[i].flowerId)
    }
  }else{
    for(let i=0;i<flowers.value.length;i++){
      selectedItems[i] = false
    }
    flowerIds.length = 0;
  }
}


async function updateCount(flowerId) {
  try {
    const response = await axios.put(`/cart/updateCount/${userId.value}/${flowerId}/${ccc.value}`, {
      headers: {
        'Authorization': loginStore.loginToken
      }
    });
    // 修改成功后刷新购物车数据
    window.location.reload();
    isShow.value = false;
    flowers.value = response.data.flowers;
    count.value = response.data.count;
  } catch (err) {
    //error.value = '修改失败';
    alert('修改失败');
    window.location.reload();
    console.error(err);
  }
}

// async function addFlower(flowerId,userId,count) {
//   try {
//     const response = await axios.post(`/cart/addFlower/${user_id}/${flower_id}/${count}`, {
//       headers: {
//         'Authorization': loginStore.loginToken
//       }
//     });
//   } catch (err) {
//     error.value = '添加失败';
//     console.error(err);
//   }
// }

let flowerIds = reactive([]); // 存储选中的商品ID
let selectedItems = reactive([]); // 存储选中的商品ID

// 多选/取消多选
function updateSelectAll(index,flowerId) {
  flowerIds = flowerIds.filter(num => num !== flowerId);
  if(selectedItems[index]){
    flowerIds.push(flowerId)
  }
  console.log(flowerIds);
}

// 删除选中的商品
async function deleteSelectedFlowers() {
  try {
    const response = await axios.delete(`/cart/deleteFlowers/${userId.value}/${flowerIds}`, {
      headers: {
        'Authorization': loginStore.loginToken
      }
    });
    // 删除成功后刷新购物车数据
    if (response.data.flowers==null) {
      // 购物车为空，刷新页面
      console.log('购物车为空');
      window.location.reload();

    } else {
      // 购物车不为空，刷新购物车数据
      flowers.value = response.data.flowers;
      count.value = response.data.count;
      flowerIds = []; // 清空选中的商品ID
    }
    location.reload(true);
  } catch (err) {
    window.location.reload();
  }
}


function handleChange(val) {
  ccc.value = val;
}
</script>

<style scoped>
.shopping-cart {
  width: 800px;
  min-height: 300px;
  margin: 0 auto;
  padding: 20px;
  margin-bottom: 50px;
}

.cart-table {
  width: 100%;
  border-collapse: collapse;
}

.cart-table th,
.cart-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.cart-table th {
  background-color: #f2f2f2;
}

.flower-img {
  width: 50px;
  height: 50px;
  margin-right: 10px;
}

.delete-btn,
.delete-selected-btn,
.checkout-btn,
.change-btn {
  padding: 5px 10px;
  cursor: pointer;
  border: none;
  border-radius: 4px;
  color: white;
}

.delete-btn {
  background-color: #dc3545;
}

.change-btn {
  margin-left: 10px;
  background-color: #007bff;
}

.delete-selected-btn {
  background-color: #dc3545;
}

.checkout-btn {
  background-color: #5cb85c;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

/* 新窗口 */
.dialog-content{
    display: flex;
    width:70%;
    margin: 0 auto;
  }
  .dialog-image{
    width: 200px;
    height: 200px;
    margin: 0 20px 20px 0;
  }
  .flower-info{
    display: flex;
    line-height: 30px;
  }
  .input-number{
    transition: fixed;
    left:330px;
  }
</style>